package controller

import (
	"github.com/gin-gonic/gin"
	"shop-bean/constant"
	"shop-bean/model"
	"shop-bean/request"
	"shop-common/library/serializer"
	"shop-common/library/variables"
	"shop-common/utils/contextArgs"
	"shop-common/utils/queryWrapper"
	"shop-service/business"
)

type StoreCategoryController struct {
}

// @Tags 分类管理
// @Summary 获取全部分类
// @Security ApiKeyAuth
// @function: List
// @Accept  json
// @Produce  json
// @Param type query int true "分类类型 1 产品分类，2 附件分类"
// @Success 200 {object} string "{"code":1," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /product/category/list [get]
func (*StoreCategoryController) List(ctx *gin.Context) {
	_type, err := contextArgs.GetUriIntQuery(ctx, "type")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	if _type != 2 {
		list, err := business.ServiceImpl().StoreCategoryService.FindJoin(uint8(_type))
		if err != nil {
			serializer.Fail(ctx, serializer.PublicQueryErr)
			return
		}

		serializer.SuccessData(ctx, "", list)
	} else {
		simpleList, err := business.ServiceImpl().StoreCategoryService.FindSimple(uint8(_type))
		if err != nil {
			serializer.Fail(ctx, serializer.PublicQueryErr)
			return
		}

		serializer.SuccessData(ctx, "", simpleList)
	}
}

// @Tags 分类管理
// @Summary 获取分类信息
// @Security ApiKeyAuth
// @function: Info
// @Param categoryId path string true "分类ID"
// @Success 200 {object} string "{"code":1," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /product/category/info/{categoryId} [get]
func (*StoreCategoryController) Info(ctx *gin.Context) {
	categoryId, err := contextArgs.GetUriIntPath(ctx, "categoryId")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	_type, err := contextArgs.GetUriIntQuery(ctx, "type")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	info, err := business.ServiceImpl().StoreCategoryService.FindById(categoryId, uint8(_type))
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	serializer.SuccessData(ctx, "", info)
}

// @Tags 分类管理
// @description: 新增分类
// @Summary 新增分类
// @Security ApiKeyAuth
// @function: Save
// @Accept  json
// @Produce  json
// @Param data body request.StoreCategoryRequest true "请求参数"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /product/category [post]
func (*StoreCategoryController) Save(ctx *gin.Context) {
	form := request.StoreCategoryRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	entity := &model.StoreCategory{
		ParentId:     form.ParentId,
		CategoryName: form.CategoryName,
		Type:         form.Type,
		Status:       form.Status,
		Seq:          form.Seq,
	}

	if form.BigAttachment != nil {
		entity.BigId = form.BigAttachment.AttId
	}

	if form.IconAttachment != nil {
		entity.IconId = form.IconAttachment.AttId
	}

	err := variables.GormDB().Create(entity).Error
	if err != nil {
		serializer.Fail(ctx, serializer.PublicCreateErr)
		return
	}

	serializer.Success(ctx, "")
}

// @Tags 分类管理
// @description: 编辑分类
// @Summary 编辑分类
// @Security ApiKeyAuth
// @function: Update
// @Accept  json
// @Produce  json
// @Param data body request.StoreCategoryRequest true "请求参数"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /product/category [put]
func (*StoreCategoryController) Update(ctx *gin.Context) {
	form := request.StoreCategoryRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	if form.CategoryId == 0 {
		serializer.Fail(ctx, "categoryId不能为空")
		return
	}

	if form.CategoryId == form.ParentId {
		serializer.Fail(ctx, "分类的上级不能是自己本身")
		return
	}

	categoryDB, err := business.ServiceImpl().StoreCategoryService.FindOne(queryWrapper.Eq("category_id", form.CategoryId))
	if err != nil {
		serializer.Fail(ctx, "不能修改分类类型")
		return
	}

	if form.Type != categoryDB.Type {
		serializer.Fail(ctx, "")
		return
	}

	//如果从下线改成正常，则需要判断上级的状态
	if categoryDB != nil && categoryDB.Status == constant.GLOBAL_DISABLE && form.Status == constant.GLOBAL_ENABLE && form.ParentId != 0 {
		query := queryWrapper.Eq("category_id", form.CategoryId).And(queryWrapper.Eq("parent_id", form.ParentId))
		parentCategory, err := business.ServiceImpl().StoreCategoryService.FindOne(query)
		if err != nil {
			serializer.Fail(ctx, serializer.PublicUpdateErr)
			return
		}

		if parentCategory.ParentId > 0 || parentCategory.Status == constant.GLOBAL_DISABLE {
			serializer.Fail(ctx, "修改失败，上级分类不存在或者不为正常状态！")
			return
		}
	}

	err = business.ServiceImpl().StoreCategoryService.Updates(&form)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}
	serializer.Success(ctx, "")
}

// @Tags 分类管理
// @description: 删除分类
// @Summary 删除分类
// @Security ApiKeyAuth
// @function: Delete
// @Accept  json
// @Produce  json
// @Param categoryId path int true "分类Id"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /product/category/{categoryId} [delete]
func (*StoreCategoryController) Delete(ctx *gin.Context) {
	categoryId, err := contextArgs.GetUriIntPath(ctx, "categoryId")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	// 查询父级
	infoDB, err := business.ServiceImpl().StoreCategoryService.FindOne(queryWrapper.Eq("parent_id", categoryId))

	if err != nil {
		serializer.Fail(ctx, serializer.PublicDeleteErr)
		return
	}

	if infoDB != nil {
		serializer.Fail(ctx, "请删除子分类，再删除该分类!")
		return
	}

	err = variables.GormDB().Delete(&model.StoreCategory{}, categoryId).Error
	if err != nil {
		serializer.Fail(ctx, serializer.PublicDeleteErr)
		return
	}
	serializer.Success(ctx, "")
}
